<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/5/005
 * Time: 16:56
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\Product as ProductModel;
use app\api\validate\IDMustBePostiveInt;
use app\api\validate\ProductValidate;
use app\lib\exception\ProductException;

class Product extends BaseController {

    /**
     * 根据 cid 和 key 获取产品列表
     * 可传入 sort 进行排序
     * @param $cid
     * @param $key
     * @param string $sort
     * @return \think\Paginator
     * @throws ProductException
     */
    public function getProductListByCidKey($cid, $key, $sort = '') {
        (new ProductValidate())->scene('list')->goCheck();

        $product = ProductModel::getProductListByCidKey($cid, $key, $sort);
        if ($product->isEmpty()) {
            throw new ProductException();
        }

        return $product;
    }

    /**
     * 获取产品详情
     * @param $id
     * @return mixed
     * @throws ProductException
     */
    public function info($id) {
        (new IDMustBePostiveInt())->goCheck();
        $product = ProductModel::getProductInfo($id);
        if (!$product) {
            throw new ProductException();
        }

        return $product;
    }

    /**
     * 返回产品所有属性，并且根据已选择的属性设置可选状态
     * @param $id
     * @param $select_ids
     * @return mixed
     * @throws ProductException
     */
    public function getProductAttr($id, $select_ids = '') {
        (new IDMustBePostiveInt())->goCheck();
        $attr = ProductModel::getProductAttr($id, $select_ids);
        if (!$attr) {
            throw new ProductException([
                'msg' => '产品属性不存在',
                'errorCode' => 80003
            ]);
        }

        return $attr;
    }
}